package com.kzw.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;

import org.apache.commons.lang3.StringUtils;

import com.kzw.entity.Clazz;
import com.kzw.service.ClazzService;

import my.json.Jackson;
import my.mvc.Annotation.JSONOutput;
import my.mvc.RequestContext;
import my.util.ResponseUtils;
import my.vo.Page;
import my.vo.Record;

public class ClazzAction {

	private ClazzService clazzService = new ClazzService();
	
	/**
	 * 班级列表
	 * */
	public void list(RequestContext rc) throws ServletException, IOException {
		int pageNo = rc.param("page", 1);
		int pageSize = rc.param("limit", 15);
		Page<Clazz> page = new Page<>(pageNo, pageSize);
		
		String orderBy = rc.param("orderBy");
		String orderDir = rc.param("orderDir");
		if(StringUtils.isNotBlank(orderBy)) {
			page.setOrderBy(orderBy);
			page.setOrder(orderDir);
		}
		
		Record record = clazzService.findPage(page);
		//输出JSON
		String json = Jackson.me().toJson(record);
		ResponseUtils.renderJson(rc.response(), json);
	}
	
	/**
	 * 增加或修改班级
	 * */
	public void save(RequestContext rc) throws ServletException, IOException {
		
		// 将请求参求自动包装成Bean对象 
		Clazz clazz = rc.form(Clazz.class);
		// id="" 自动包装成了 id=0
		if(clazz.getId() == 0) {
			// 新增
			clazzService.save(clazz);
		} else {
			// 修改
			clazzService.update(clazz);
		}
		
		// 重定向到一个查询请求
		rc.redirect(rc.contextPath() + "/action/clazz/list");
	}
	
	/**
	 * 删除班级
	 * */
	@JSONOutput
	public Record del(RequestContext rc) throws ServletException, IOException {
		long id = rc.param("id", 0L);
		clazzService.remove(id);
		
		return new Record(true);
	}
	
	/**
	 * 编辑班级之前，用于回显
	 * */
	public void get(RequestContext rc) throws ServletException, IOException {
		String id = rc.param("id");
		if(id!=null && !id.equals("")) {
			Clazz clazz = clazzService.findById(Long.parseLong(id));	
			rc.reqAttr("clazz", clazz);
			rc.forward("/pages/clazz_form.jsp");
		}
	}
	
	/**
	 * ajax获得所有班级
	 * */
	public void ajax(RequestContext rc) throws ServletException, IOException {
		List<Clazz> clazzList = clazzService.findAll();
		String json = Jackson.me().with(Clazz.class, "id", "name").toJson(clazzList);
		ResponseUtils.renderJson(rc.response(), json);
	}
	
	/**
	 * 批量删除
	 * */
	@JSONOutput
	public Record multiDel(RequestContext rc) throws ServletException, IOException {
		String ids = rc.param("ids");
		if(StringUtils.isNotBlank(ids)) {
			clazzService.multiDel(ids);
		}
		
		return new Record();
	}
	
}
